package com.wf.demo.sys.controller;

import com.wf.demo.info.util.Result;
import com.wf.demo.sys.annotation.SysLog;
import com.wf.demo.sys.dao.RoleDAO;
import com.wf.demo.sys.pojo.Role;
import com.wf.demo.sys.pojo.User;
import com.wf.demo.sys.service.RoleService;
import com.wf.demo.sys.shiro.ShiroUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.HtmlUtils;

import java.util.List;

/**
 * @Auther: wf
 * @Date: 2019/12/20 16:25
 * @Description:
 */
@RestController
public class RoleController {
    @Autowired
    RoleService roleService;
    @GetMapping("/roles")
    @RequiresPermissions("sys:role")
    public List<Role> list(){
        return roleService.list();
    }

    @GetMapping("/roles/{id}")
    @RequiresPermissions("sys:role")
    public Object get(@PathVariable("id")long id ){
        Role bean =roleService.get(id);
        return bean;
    }
    @SysLog("保存角色")
    @PostMapping("/roles")
    @RequiresPermissions("sys:role")
    public Object register(@RequestBody Role role) {
        String name =  role.getRoleName();
        //将发送的role名字进行转义，防止出错
        name = HtmlUtils.htmlEscape(name);
        role.setRoleName(name);
        boolean exist = roleService.isExist(name);
        if(exist){
            String message ="角色名已经存在,不能使用";
            return Result.addFail(message);
        }
       roleService.add(role);
        return Result.addSuccess(role);
    }

    @SysLog("修改角色")
    @PutMapping("/roles")
    @RequiresPermissions("sys:role")
    public Object update(@RequestBody Role role) throws Exception{

        boolean exist = roleService.isExist(role);
        if(exist){
            String message ="角色名已经存在,不能使用";
            return Result.addFail(message);
        }
        roleService.add(role);
        return Result.addSuccess(role);
    }

    @SysLog("删除角色")
    @DeleteMapping("/roles/{id}")
    @RequiresPermissions("sys:role")
    public String delete(@PathVariable("id")long id ){
        roleService.delete(id);
        return null;
    }
}
